package qingyu.ai.adapter;

import android.content.Context;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

import qingyu.ai.R;

public class FeeadBackAdapter extends RecyclerView.Adapter<FeeadBackAdapter.FeedBackViewHolder> {

    private Context context;
    private List<String> uris = new ArrayList<>();
    private View.OnClickListener listener;
    private OnItemClickListener itemClickListener;

    public FeeadBackAdapter(Context context) {
        this.context = context;
    }

    public void setUris(List<String> uris) {
        this.uris = uris;
        notifyDataSetChanged();
    }

    public void setListener(View.OnClickListener listener) {
        this.listener = listener;
    }

    public void setItemClickListener(OnItemClickListener listener) {
        this.itemClickListener = listener;
    }

    @Override
    public FeedBackViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new FeedBackViewHolder(LayoutInflater.from(context).inflate(R.layout.item_feedback_list, parent, false));
    }

    @Override
    public void onBindViewHolder(FeedBackViewHolder holder, final int position) {
        if (position < uris.size()) {
            holder.itemView.setOnClickListener(null);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClickListener.onItemClick(position);
                }
            });
            holder.imageView.setImageURI(Uri.parse(uris.get(position)));
        } else {
            if (uris.size() < 4) {
                holder.itemView.setOnClickListener(null);
                holder.imageView.setImageResource(R.mipmap.icon_add);
                holder.imageView.setOnClickListener(listener);
                return;
            }
            ((RelativeLayout) holder.itemView).removeAllViews();
        }
    }

    @Override
    public int getItemCount() {
        return uris != null ? uris.size() + 1 : 1;
    }

    static class FeedBackViewHolder extends RecyclerView.ViewHolder {
        public ImageView imageView;

        public FeedBackViewHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.iv_item_feedback);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }
}
